var tempI = 1;
var tempF = 1;
// 允许上传的图片类型
var allowTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'];
// 1024KB，也就是 1MB
var maxSize = 1024 * 1024 * 5;
// 图片最大宽度
var maxWidth = 300;
// 最大上传图片数量
var maxCount = 1;
//上传文件
var $uploaderFiles = $('.weui_uploader_files');
// 删除文件按钮
var $delBtn = $('.weui-icon-delete');
// 上传的图片地址
var URL = '';
// 图片地址数组
var URLARR = [];

$(function () {
    $('#input-name').val(sessionStorage.getItem('hmdj_nickname'));
});

// 确定按钮
$(document).on('click', '.submit-btn', function () {
    // 验证信息是否正确
    var params = { nickname: $.trim($('#input-name').val()), photo: sessionStorage.getItem('hmdj_photo') };
    for (i in params) {
        if (params[i] == '') {
            weui.alert('请输入完整信息');
            return false;
        }
    }
    // 提交信息
    var url = '';
    if(URLARR.length >= 1) {
        url = URLARR[0].url;
    }
    var result = Model.user.editInfo({ nickname: params.nickname, photo: params.photo, media_id: url });
    if (result.code) {
        Common
            .fn
            .formatOutput(result);
        return false;
    }
    weui.alert(result.data, function () {
        location.href = 'mine.html';
    });
});

function fileChange(obj) {
    var files = obj[0].files;
    // 如果没有选中文件，直接返回
    if (files.length === 0) {
        return;
    }
    for (var i = 0, len = files.length; i < len; i++) {
        var file = files[i];
        var reader = new FileReader();
        // 如果类型不在允许的类型范围内
        if (allowTypes.indexOf(file.type) === -1) {
            weui.alert('该类型不允许上传');
            continue;
        }
        if (file.size > maxSize) {
            weui.alert('图片太大，不允许上传');
            continue;
        }
        reader.onload = function (e) {
            var img = new Image();
            var time = new Date().getTime();
            var fileid = 'file' + time;
            img.onload = function () {
                // 不要超出最大宽度
                var w = Math.min(maxWidth, img.width);
                // 高度按比例计算
                var h = img.height * (w / img.width);
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                // 设置 canvas 的宽度和高度
                canvas.width = w;
                canvas.height = h;
                ctx.drawImage(img, 0, 0, w, h);
                var base64 = canvas.toDataURL('image/png');
                // 插入到预览区
                var $preview = $(
                    '<li class="weui_uploader_file weui_uploader_status" data-num="' + tempI + '" i' +
                    'd="' + fileid + '" style="background-image:url(' + base64 + ');position: relat' +
                    'ive;"><a href="javascript:;" class="close-btn"><img src="../img/icon/close.png' +
                    '" class="upload-item-close"></a><div class="weui_uploader_status_content">0%</' +
                    'div></li>'
                );
                $uploaderFiles.append($preview);
                var num = URLARR.length;
                // 删除图片按钮
                $('.close-btn').on('click', function () {
                    var that = $(this).parent();
                    delBtn(that);
                });
                //点击删除按钮，删除相应已上传图片
                function delBtn(that) {
                    // 删除对应的上传文件
                    var item = that.attr('data-num');
                    $('#file-' + item).remove();
                    //对应的图片删除
                    that.remove();
                    //删除后，重新计算当前剩余图片数量 end 删除数组中对应的图片信息
                    for (var i = 0; i < URLARR.length; i++) {
                        if (URLARR[i].id == item) {
                            URLARR.splice(i, 1);
                        }
                    }
                }
                var progress = 0;

                function uploading() {
                    $preview
                        .find('.weui_uploader_status_content')
                        .text(progress++ + '%');
                    // 上传文件个数大于最大个数时，提示最多只能上传图片数量，清空图片和计数器
                    if (URLARR.length >= maxCount) {
                        weui.alert('最多只能上传' + maxCount + '张图片');
                        $('.weui_uploader_files li:last').remove();
                        return false;
                    } else {
                        // 进度小于100%时，上传继续
                        if (progress <= 100) {
                            // 禁用上传按钮
                            $('#file-' + tempI).attr('disabled', true);
                            $('#showTooltips').removeClass('submit-btn');
                            $('#showTooltips').text('图片上传中...');
                            setTimeout(uploading, 20);
                        } else {
                            // 进度达到100%时，上传完毕，并当上传数量至少大于1时，提示文件上传成功 如果是失败，塞一个失败图标
                            $preview
                                .removeClass('weui_uploader_status')
                                .find('.weui_uploader_status_content')
                                .remove();
                            $('.uploads-files').append(obj);
                            obj.css('display', 'none');
                            obj.attr('disabled', false);
                            // 进行图片上传
                            var formData = new FormData($('#uploadform')[0]),
                                result = Model
                                    .uploads
                                    .do 
                                        (formData);
                                        URL = result;
                                        URLARR.push({id: tempF, url: URL});
                                        tempF++;
                                        $('#showTooltips').text('确定');
                                        $('#showTooltips').addClass('submit-btn');
                                        tempI++;
                                        // 生成新的input
                                        $('#uploader-wrapper').append(
                                            '<input class="weui_uploader_input js_file" name="file" id="file-' + tempI + '"' +
                                            ' type="file" accept="image/jpg,image/jpeg,image/png,image/gif" multiple="multi' +
                                            'ple" onchange="fileChange($(this))" />'
                                        );
                                    }
                                }
                        }
                        setTimeout(uploading, 20);
                    };
                    img.src = e.target.result;
                };
                reader.readAsDataURL(file);
            }
        }

        /* $(document).on('submit', '#data', function() {
    $("#data").ajaxSubmit(function (data) {
        alert('图片上传成功:' + data);
        URL = data;
        URLARR.push({
            id: tempF,
            url: URL
        });
        tempF++;
        $('#showTooltips').text('确定');
        $('#showTooltips').addClass('submit-btn');
    });
    return false;
}); */
